//
//  ChangePhoneVC.m
//  EnterpriseEdition
//  Created by ypj on 2021/10/9.
//
#import "ChangePhoneVC.h"

@interface ChangePhoneVC ()

@property (nonatomic, assign) NSInteger timeout;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) YLUserInfo *info;

@end

@implementation ChangePhoneVC
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self layoutCustomNav:self.view title:@"修改手机号"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
     self.phoneTF.delegate = self;
     self.codeTF.delegate = self;
     self.info = [YLUserMgr fetchUser];
     self.currentPhone.text = [NSString stringWithFormat:@"当前手机号:%@",self.info.phone];
    [self.sureButton createBordersWithColor:nil withCornerRadius:5.0 andWidth:0];
    [self.clearButton whenTapped:^{
        self.phoneTF.text = @"";
    }];
    [self.sureButton whenTapped:^{
        [self.view endEditing:YES];
        [self commitUpdateInfo];
    }];
    [self.view whenTapped:^{
        [self.view endEditing:YES];
    }];
}

- (IBAction)codeButtonClick:(UIButton *)sender {
    [self.view endEditing:YES];
    [self getCodeData];
}

-(void)getCodeData{
    if (![_phoneTF.text isValidPhone]){
        showAlert(@"手机号码不正确");
        return;
    }
//     NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary: @{
//                @"phone":self.phoneTF.text,
//    }];
    self.codeButton.enabled = NO;
  
    
    
    NSString *url = [NSString stringWithFormat:@"%@?phone=%@",BEFORE_SMS_URL,self.phoneTF.text];

    [MSNetworkManager postRevertUrl:url params:@{} success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        
        if (isSuccess) {
            self.timeout = kCodeTime;
           [self.codeButton setTitle:[NSString stringWithFormat:@"%d秒", kCodeTime] forState:UIControlStateNormal];
            showAlert(@"获取验证码成功");
           [self applicationEnterBackground];
           BD_WEAKSELF
           [[kNotifyCenter rac_addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil] subscribeNext:^(NSNotification * _Nullable note){
               [weakSelf applicationEnterBackground];
           }];
        }
        
        
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
    } withShowHud:YES];
    
    
  
}

- (void)applicationEnterBackground {
    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
    //加入定时器，用来控制后台运行时间
    if (!_timer) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
        //[_timer fire];
    }
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

- (void)countDown {
    _timeout--;
    [self.codeButton setTitle:[NSString stringWithFormat:@"%ld秒",(long)_timeout] forState:UIControlStateNormal];
    if (_timeout == 0){
        [self msgCodeFail];
    }
}

- (void)msgCodeFail{
    [_timer invalidate];
     _timer = nil;
    [_codeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
     _codeButton.enabled = YES;
     _timeout = kCodeTime;
}

-(void)commitUpdateInfo{
    [self.view endEditing:YES];
    if (![_phoneTF.text isValidPhone]){
        showAlert(@"手机号码不正确");
        return;
    }
    if (_codeTF.text.length== 0) {
        showAlert(@"验证码不能为空");
        return;
    }
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:@"2" forKey:@"cmd"];
    [params setObject:self.phoneTF.text forKey:@"phone"];
    [params setObject:self.codeTF.text forKey:@"code"];
    
    
    [MSNetworkManager postRevertUrl:Post_UpDateUserInfo params:params success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        
        if (isSuccess) {
//            NSDictionary *objects = resonseObj[@"data"];
//            [self saveUserInfo:objects];
//            YLUserInfo * info = [YLUserMgr fetchUser];
//             if (info == nil) info = [[YLUserInfo alloc] init];
//             info.authorization = resDic[@"authorization"];
//             [YLUserMgr saveUser:info];
             showAlert(@"手机号更换成功");
            kUserDefaultSetBool(YES, kRefreshStr);
            
            [self getUserInfo:^(BOOL isSuccess) {
                if (isSuccess) {
                    [self.navigationController popViewControllerAnimated:YES];
                }
            }];
            
        }
        
        
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
    } withShowHud:YES];
    
  
}

-(void)textFieldDidChangeSelection:(UITextField *)textField{
    if (textField == self.phoneTF){
        if (textField.text.length > 11){
            textField.text = [textField.text substringToIndex:11];
      }
   }
    if (textField == self.codeTF) {
        if (textField.text.length > 6){
            textField.text = [textField.text substringToIndex:6];
        }
    }
}
@end
